//
//  DoorSystemAlarmAccessViewController.m
//  RONGAO
//
//  Created by ZhangYeKun on 2017/2/24.
//  Copyright © 2017年 wei wang. All rights reserved.
//

#import "DoorSystemAlarmAccessViewController.h"
#import "AlarmListViewController.h"
#import "Alarm433Device.h"
#import "AVIOCTRLDEFuserdefineds.h"
#import "wifi_433_info.h"

@interface DoorSystemAlarmAccessViewController ()<UITableViewDelegate,UITableViewDataSource,MyCameraDelegate>
/** tableView **/
@property(nonatomic,strong) UITableView *tableView;
/** deviceListArr **/
@property(nonatomic,strong) NSMutableArray *deviceListArr;
@end

@implementation DoorSystemAlarmAccessViewController

- (void)viewWillAppear:(BOOL)animated {
    
    if (self.camera != nil)
    self.camera.delegate2 = self;
    [super viewWillAppear:animated];
    SmsgAVIoctrlGetAllDevicesReq *s = malloc(sizeof(SmsgAVIoctrlGetAllDevicesReq));
    memset(s, 0, sizeof(SmsgAVIoctrlGetAllDevicesReq));
    
    [self.camera sendIOCtrlToChannel:0
                                Type:IOTYPE_USER_IPCAM_433_GETDIVICES_LIST_REQ
                                Data:(char *)s
                            DataSize:sizeof(SmsgAVIoctrlGetAllDevicesReq)];
    free(s);
    
    isRecvDev = NO;

}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setNavigationStyle];

   
}


- (void)viewDidUnload {
    
    self.camera = nil;
    self.deviceListArr = nil;
    [super viewDidUnload];
    
}




- (NSInteger)rowToTypeInt:(NSInteger)row {
    NSInteger typeInt = 0;
    
    switch (row) {
        case 0:
            typeInt = ST_REMOTER;
            break;
        case 1:
            typeInt = ST_DOOR;
            break;
        case 2:
            typeInt = ST_INFRARED;
            break;
        case 3:
            typeInt = ST_SMOKE;
            break;
        case 4:
            typeInt = ST_GAS;
            break;
        case 5:
            typeInt = ST_ALARM;
            break;
        default:
            typeInt = ST_LOCAL;
            break;
    }
    
    return typeInt;
}

- (NSString *)rowToTitle:(NSInteger)row {
    NSString *str = [NSString stringWithFormat:@""];
    
    switch (row) {
        case 0:
            str = @"遥控器";
            break;
        case 1:
            str = @"门磁";
            break;
        case 2:
            str = @"红外";
            break;
        case 3:
            str = @"烟感";
            break;
        case 4:
            str = @"气感";
            break;
        case 5:
            str = @"警笛";
            break;
        default:
            str = @"其他";
            break;
    }
    
    return str;
}


#pragma mark - --------------------------UITableView dataSource--------------------------

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (section == 0) {
        int row = 7;
        
        return row;
    } else {
        return 0;
    }
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSUInteger section = [indexPath section];
    NSUInteger row = [indexPath row];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (cell == nil) {
        
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cell"];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        cell.textLabel.textColor = [UIColor colorWithHexString:@"666666"];
        cell.detailTextLabel.textColor = [UIColor colorWithHexString:@"84807f"];
        
    }
    
    if (section == 0) {
        
        NSString *text = nil;

        if (row == ST_REMOTER_ROW_INDEX) {
            NSInteger num = 0;
            for (Alarm433Device *a433dev in self.deviceListArr) {
                if (ST_REMOTER == a433dev.device_type) {
                    num++;
                }
            }
            
            cell.textLabel.text = [self rowToTitle:ST_REMOTER_ROW_INDEX];
            NSString *str = [NSString stringWithFormat:@"已添加%ld个", (long)num];
            text = [[NSString alloc] initWithString:str];
            cell.detailTextLabel.text = text;
            
      
        } else if (row == ST_DOOR_ROW_INDEX) {
            NSInteger num = 0;
            for (Alarm433Device *a433dev in self.deviceListArr) {
                if (ST_DOOR == a433dev.device_type) {
                    num++;
                }
            }
            
            cell.textLabel.text = [self rowToTitle:ST_DOOR_ROW_INDEX];
            
            NSString *str = [NSString stringWithFormat:@"已添加%ld个", (long)num];
            text = [[NSString alloc] initWithString:str];
            cell.detailTextLabel.text = text;
   
        } else if (row == ST_INFRARED_ROW_INDEX) {
            NSInteger num = 0;
            for (Alarm433Device *a433dev in self.deviceListArr) {
                if (ST_INFRARED == a433dev.device_type) {
                    num++;
                }
            }
            
            cell.textLabel.text = [self rowToTitle:ST_INFRARED_ROW_INDEX];
            
            NSString *str = [NSString stringWithFormat:@"已添加%ld个", (long)num];
            text = [[NSString alloc] initWithString:str];
            cell.detailTextLabel.text = text;
     
        } else if (row == ST_SMOKE_ROW_INDEX) {
            NSInteger num = 0;
            for (Alarm433Device *a433dev in self.deviceListArr) {
                if (ST_SMOKE == a433dev.device_type) {
                    num++;
                }
            }
            
            cell.textLabel.text = [self rowToTitle:ST_SMOKE_ROW_INDEX];
            
            NSString *str = [NSString stringWithFormat:@"已添加%ld个", (long)num];
            text = [[NSString alloc] initWithString:str];
            cell.detailTextLabel.text = text;
            

        } else if (row == ST_GAS_ROW_INDEX) {
            NSInteger num = 0;
            for (Alarm433Device *a433dev in self.deviceListArr) {
                if (ST_GAS == a433dev.device_type) {
                    num++;
                }
            }
            
            cell.textLabel.text = [self rowToTitle:ST_GAS_ROW_INDEX];
            
            NSString *str = [NSString stringWithFormat:@"已添加%ld个", (long)num];
            text = [[NSString alloc] initWithString:str];
            cell.detailTextLabel.text = text;
            

        } else if (row == ST_ALARM_ROW_INDEX) {
            NSInteger num = 0;
            for (Alarm433Device *a433dev in self.deviceListArr) {
                if (ST_ALARM == a433dev.device_type) {
                    num++;
                }
            }
            
            cell.textLabel.text = [self rowToTitle:ST_ALARM_ROW_INDEX];
            
            NSString *str = [NSString stringWithFormat:@"已添加%ld个", (long)num];
            text = [[NSString alloc] initWithString:str];
            cell.detailTextLabel.text = text;
            

        } else if (row == ST_OTHER_ROW_INDEX) {
            NSInteger num = 0;
            for (Alarm433Device *a433dev in self.deviceListArr) {
                if (ST_REMOTER != a433dev.device_type &&
                    ST_DOOR != a433dev.device_type &&
                    ST_INFRARED != a433dev.device_type &&
                    ST_SMOKE != a433dev.device_type &&
                    ST_GAS != a433dev.device_type &&
                    ST_ALARM != a433dev.device_type) {
                    num++;
                }
            }
            
            cell.textLabel.text = [self rowToTitle:ST_OTHER_ROW_INDEX];
            
            NSString *str = [NSString stringWithFormat:@"已添加%ld个", (long)num];
            text = [[NSString alloc] initWithString:str];
            cell.detailTextLabel.text = text;
            
    
        }

        
    }
    
    return cell;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 54.f;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    
    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return CGFLOAT_MIN;
    
}
#pragma mark - --------------------------UITableView delegate--------------------------

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
  
    if (isRecvDev) {
    } else {
        return [SVProgressHUD showInfoWithStatus:@"加载中..."];
    }
 
    
        NSInteger type = [self rowToTypeInt:indexPath.row];
        NSLog(@"type:%ld", (long)type);
        
        NSMutableArray *devListArr = [[NSMutableArray alloc] init];
        
        
        
        for (int i=0; i<[self.deviceListArr count]; i++) {
            Alarm433Device *dev = (Alarm433Device *)[self.deviceListArr objectAtIndex:i];
            
            if (type == dev.device_type) {
                [devListArr addObject:dev];
            }
        }
        
        AlarmListViewController *controller0 = [[AlarmListViewController alloc] init];
        controller0.camera = self.camera;
        controller0.typeInt = type;
        self.hidesBottomBarWhenPushed = YES;

        controller0.deviceListArr = devListArr;
        [self.navigationController pushViewController:controller0 animated:YES];


    
    
}


#pragma mark - MyCameraDelegate Methods
- (void)camera:(MyCamera *)camera_ _didReceiveIOCtrlWithType:(NSInteger)type Data:(const char *)data DataSize:(NSInteger)size {
    NSLog(@"ADSVC _didReceiveIOCtrlWithType type:%lx", (long)type);
    
    if (camera_ == self.camera) {
        
        if (type == IOTYPE_USER_IPCAM_433_GETDIVICES_LIST_RESP) {
            
            SmsgAVIoctrlGetAllDevicesResp *s = (SmsgAVIoctrlGetAllDevicesResp*)data;
            
            isRecvDev = YES;
            
            int num = s->devices_.num_;
            
            NSLog(@"s->result_:%d, num:%d", s->result_, num);
            if (0 == s->result_) {
                
                [self.deviceListArr removeAllObjects];
                for (int i=0; i<num; i++) {
                    Alarm433Device *dev = [[Alarm433Device alloc] init];
                    
                    dev.device_type = s->devices_.devices_array_[i].device_type_;
                    dev.device_vender = s->devices_.devices_array_[i].device_vender_;
                    dev.key = [NSString stringWithFormat:@"%s", s->devices_.devices_array_[i].key_];
                    //dev.alias = [NSString stringWithFormat:@"%s", s->devices_.devices_array_[i].aliase_];
                    dev.alias = [[NSString alloc] initWithCString:(char*)s->devices_.devices_array_[i].aliase_ encoding:NSUTF8StringEncoding];
                    [self.deviceListArr addObject:dev];
                }
                
                
                [self.tableView reloadData];
            }
            
            
        } else if (type == IOTYPE_USER_IPCAM_433_EDITDIVICES_LIST_RESP) {
            SmsgAVIoctrlEditAllDevicesResp *s = (SmsgAVIoctrlEditAllDevicesResp*)data;
            NSLog(@"AlarmDeviceSettingViewController IOTYPE_USER_IPCAM_433_EDITDIVICES_LIST_RESP s->result_:%d, s->type:%d, s->alarm_type:%d, s->devices_.num_:%d", s->result, s->type, s->alarm_type, s->devices_.num_);
            
            isRecvDev = YES;
            
            if (0 == s->result) {
                
                
                [self.deviceListArr removeAllObjects];
                
                if (EDIT_433_LIST_TYPE_GET_ALARM_INFO == s->type) {
                    NSInteger num = s->devices_.num_;
                    
                    camera_.orgModeValue1 = s->alarm_type;
                    camera_.newModeValue1 = camera_.orgModeValue1;
                    
                    
                    [camera_.externalDeviceListArr removeAllObjects];
                    
                    for (int i=0; i<num; i++) {
                        Alarm433Device *dev = [[Alarm433Device alloc] init];
                        dev.key = [NSString stringWithUTF8String:s->devices_.devices_array_[i].key_];
                        dev.alias = [NSString stringWithUTF8String:s->devices_.devices_array_[i].aliase_];
                        
                        dev.device_type = s->devices_.devices_array_[i].device_type_;
                        dev.device_vender = s->devices_.devices_array_[i].device_vender_;
                        
#if defined(BUILD_FOR_GANSU_CAM)
                        dev.device_alarmed = s->devices_.devices_array_[i].device_alarmed;
                        dev.alarm_ptz_preset = s->devices_.devices_array_[i].alarm_ptz_preset;
                        dev.device_closed = s->devices_.devices_array_[i].device_closed;
#endif
                        
                        dev.new_device_alarmed = dev.device_alarmed;
                        dev.new_alarm_ptz_preset = dev.alarm_ptz_preset;
                        dev.new_device_closed = dev.device_closed;
                        
                        
                        [self.deviceListArr addObject:dev];
                        
                        NSLog(@"i:%d dev.alias:%@, dev.key:%@", i, dev.alias, dev.key);
                        NSLog(@"dev.device_type:%ld, dev.device_vender:%ld, dev.device_alarmed:%ld, dev.alarm_ptz_preset:%ld, dev.device_closed:%ld", (long)dev.device_type, (long)dev.device_vender, (long)dev.device_alarmed, (long)dev.alarm_ptz_preset, (long)dev.device_closed);
                    }
                    
                    
                    [self.tableView reloadData];
                    
                }
            } else {
            }
            
            
        }
    }
}

- (void)getDevTask {
    for (int i=0; i<20; i++) {
        
        if (isRecvDev) {
            break;
        }
        
        usleep(500*1000);
    }
}


#pragma mark - AddAlarmDeviceViewDelegate Methods
- (void)didAddAlarmDevice:(NSMutableArray *)addDevListArr {
    NSLog(@"ADSVC didAddAlarmDevice addDevListArr.count:%lu", (unsigned long)addDevListArr.count);
    
    BOOL isSame = NO;
    
    if (addDevListArr) {
        for (Alarm433Device *d in addDevListArr) {
            for (Alarm433Device *dev in self.deviceListArr) {
                if ([d.key isEqualToString:dev.key]) {
                    isSame = YES;
                    break;
                }
            }
            if (isSame) {
                NSLog(@"isSame == YES; Over!");
            } else {
                NSLog(@"isSame == NO; New one!");
                [self.deviceListArr addObject:d];
            }
        }
    }
    
    NSLog(@"ADSVC didAddAlarmDevice self.deviceListArr.count:%lu", (unsigned long)self.deviceListArr.count);
    
    [self.tableView reloadData];
}


#pragma mark - AlarmListViewControllerDelegate Methods
- (void)didDelAlarmDevice:(NSMutableArray *)delDevListArr {
    NSLog(@"ADSVC didDelAlarmDevice delDevListArr.count:%lu", (unsigned long)delDevListArr.count);
    
    if (delDevListArr) {
        for (Alarm433Device *dev in delDevListArr) {
            [self.deviceListArr removeObject:dev];
        }
    }
    
    NSLog(@"ADSVC didDelAlarmDevice self.deviceListArr.count:%lu", (unsigned long)self.deviceListArr.count);
    
    [self.tableView reloadData];
}


- (void)externalDeviceListSMsgAVIoctrlGet:(MyCamera *)camera
{
    NSLog(@"externalDeviceListSMsgAVIoctrlGet");
    SmsgAVIoctrlEditAllDevicesReq *s = (SmsgAVIoctrlEditAllDevicesReq *)malloc(sizeof(SmsgAVIoctrlEditAllDevicesReq));
    memset(s, 0, sizeof(SmsgAVIoctrlEditAllDevicesReq));
    
    s->type = EDIT_433_LIST_TYPE_GET_ALARM_INFO ;
    
    [camera sendIOCtrlToChannel:0
                           Type:IOTYPE_USER_IPCAM_433_EDITDIVICES_LIST_REQ
                           Data:(char *)s
                       DataSize:sizeof(SmsgAVIoctrlEditAllDevicesReq)];
    free(s);
}


- (NSMutableArray *)deviceListArr{
    
    if (!_deviceListArr) {
        
        _deviceListArr = [NSMutableArray array];
    }
    return _deviceListArr;
}

- (UITableView *)tableView{
    
    if (!_tableView) {
        
        __weak UIView *superView = self.view;
        _tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        [superView addSubview:_tableView];
        //        _tableView.separatorStyle = UITableViewCellSelectionStyleNone;//隐藏tableView的分割线
        
        _tableView.delegate = self;
        _tableView.dataSource = self;
    }
    
    return _tableView;
    
}


- (void)setNavigationStyle{
    
    [self setLeftButtonImage:[UIImage imageNamed:@"icon_back_nor"]];
    [self setNavigationTitle:@"报警器接入" titleColor:[UIColor colorWithRed:210/255.0 green:177/255.0 blue:104/255.0 alpha:1]];
    
}

- (void)masLayoutSubview{
    
    __weak UIView *superView = self.view;
    [self.tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
        
        make.edges.mas_equalTo(superView);
        
    }];
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


@end
